from rest_framework.views import exception_handler
from rest_framework.response import Response
from django.utils import timezone
import logging

logger = logging.getLogger(__name__)


def custom_exception_handler(exc, context):
    """自定义异常处理器"""
    response = exception_handler(exc, context)
    
    if response is not None:
        # 记录异常日志
        logger.error(f"API异常: {exc}", exc_info=True)
        
        # 统一异常响应格式
        custom_response_data = {
            'code': response.status_code,
            'message': '请求处理失败',
            'errors': response.data,
            'timestamp': timezone.now().isoformat()
        }
        
        # 根据异常类型自定义消息
        if response.status_code == 400:
            custom_response_data['message'] = '请求参数错误'
        elif response.status_code == 401:
            custom_response_data['message'] = '未授权访问'
        elif response.status_code == 403:
            custom_response_data['message'] = '权限不足'
        elif response.status_code == 404:
            custom_response_data['message'] = '资源不存在'
        elif response.status_code == 405:
            custom_response_data['message'] = '请求方法不允许'
        elif response.status_code >= 500:
            custom_response_data['message'] = '服务器内部错误'
            # 生产环境不暴露详细错误信息
            custom_response_data['errors'] = {'detail': '服务器内部错误，请稍后重试'}
        
        response.data = custom_response_data
    
    return response
